<?php

namespace App\Http\Controllers;

use App\Models\UserModel;
use App\Secrice\SendNote;
use App\Sevrice\ApiJwt;
use App\Sevrice\EventGenerator;
use App\Sevrice\lisi;
use App\Sevrice\ObServer1;
use App\Sevrice\one;
use App\Sevrice\two;
use App\Sevrice\wangwu;
use App\Sevrice\Watch;
use App\Sevrice\zhangsan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;

class LoginControlle extends Controller
{
    /**
     * @param Request $request
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * 手机号发送验证码
     */
    function getCapt(Request $request)
    {
        $tel = $request->post('userTel');
        if (Cache::get($tel)) {
            return ['code' => 200, 'msg' => '请稍等一分钟'];
        }
        $note = mt_rand(1000, 9999);
//        $res=SendNote::getNote($tel,$note);
        $res = true;
        if ($res) {
            Cache::set($tel . 'a', $note, 180);
            Cache::set($tel, $note, 60);
            return ['code' => 200, 'msg' => '发送成功', 'data' => $note];
        }
        return ['code' => 400, 'msg' => '发送失败', 'data' => $note];
    }

    /**
     * @param Request $request
     * @return array
     * 短信验证码/账号密码登录
     */
    function doLogin(Request $request)
    {
        $userTel = $request->post('userTel');
        $note = $request->post('capt');
        $password = $request->post('password');
        $data = UserModel::where('user_tel', $userTel)->orwhere('user_email', $userTel)->first();
        if ($password == '') {
            $oldNote = Cache::get($userTel . 'a');
            if ($note != $oldNote || $note == '') {
                return ['code' => 400, 'msg' => '验证码有误'];
            }
            $token = ApiJwt::getToken($data['user_id']);
            return ['code' => 200, 'msg' => '登录成功', 'data' => $token];
        }
        if ($data['password'] == md5($password)) {
            //观察者观察用户登录推送信息
            $obj=new Watch();
            $obj->regsiter(new one());
            $obj->notify($data['user_nick']);
            $token = ApiJwt::getToken($data['user_id']);
            return ['code' => 200, 'msg' => '登录成功', 'data' => $token];
        }
        return ['code' => 400, 'msg' => '密码有误'];
    }

    /**
     * @param Request $request
     * 用户下线并通知相应粉丝用户
     */
    function outLogin(Request $request){
        $userId=ApiJwt::decodeToken($request->get('token'));
        $userNick=UserModel::where('user_id',$userId)->value('user_nick');
        $obj=new Watch();
        $obj->regsiter(new two());
        $obj->notify($userNick);
    }
    /**
     * @param Request $request
     * @return mixed
     * 查询用户信息
     */
    function userInfo(Request $request){
        $userId=ApiJwt::decodeToken($request->get('token'));
        $data=UserModel::where('user_id',$userId)->first()->toArray();
        return $data;
    }
}
